'''
难度 简单
题目链接 https://leetcode.cn/problems/happy-number/description/
'''

class Solution:
    # 常规循环 超时
    def isHappy1(self, n: int) -> bool:
        def 计算结果(num: int):
            res = 0
            while num:
                res += (num % 10) ** 2
                num //= 10
            return res

        结果数集合 = set()
        n = 计算结果(n)
        while True:
            if n == 1:
                return True
            elif n in 结果数集合:
                return False
            else:
                n = 计算结果(n)
    
    # 快慢循环 判断是否陷入循环
    def isHappy(self, n: int) -> bool:
        def 计算结果(num: int):
            res = 0
            while num:
                res += (num % 10) ** 2
                num //= 10
            return res

        slow, fast = n, n
        
        while True:
            # 慢的走一次 快的走两次 当他们碰头了 表明循环了
            slow = 计算结果(slow)
            fast = 计算结果(fast)
            fast = 计算结果(fast)
            if slow == 1:
                return True
            
            if slow == fast:
                break
        
        return False
    

if __name__ == '__main__':
    s = Solution()
    参数 = [
        [19],
        [2],
    ]
    预期 = [
        True,
        False,
    ]
    for k,v in enumerate(参数):
        r = s.isHappy(v[0])
        if r != 预期[k]:
            print("第{}个case不通过 期望={} 结果={}\n".format(
                k+1,
                预期[k],
                r
            ))